<template>
  <div id="chargeContainer" class="charge-container">
    <div class="no-print">
      <h1 class="charge-title">{{ $t('记账凭证') }}</h1>
      <div class="charge">
        <div class="absolute">
          <el-select v-model="voucher.fundAccountId" :disabled="operateHandle !== 'add'" size="mini" style="width: 150px;" @change="getSubjectList(voucher.fundAccountId)">
            <el-option
              v-for="item in finFundAccountList"
              :key="item.id"
              :label="item.accountName"
              :value="item.id"
            />
          </el-select>
          {{ voucher.yearMonth }}
        </div>
        <div class="display-between">
          <div>
            <el-button v-if="operateHandle !== 'edit' && operateHandle !== 'copy' && operateType!=='view'" type="primary" size="mini" @click="onSubmitAndInsert">{{ saveAndInsertLabel }}</el-button>
            <el-button v-if="operateType!=='view' " size="mini" type="primary" @click="onSubmit">保存</el-button>
            <el-button size="mini" @click="doPrint">打印</el-button>
          <!--          <el-button size="mini">保存成模板</el-button>-->
          <!--          <el-button size="mini">从模板中加载</el-button>-->
          </div>
        </div>
        <div class="display-between">
          <div class="gap10">
            <el-select v-model="voucher.voucherWordId" size="mini" style="width: 80px;" @change="getAccountNum">
              <el-option
                v-for="item in finVoucherWordList"
                :key="item.id"
                :label="item.voucherWord"
                :value="item.id"
              />
            </el-select>
            <span>
              <el-input-number v-model="voucher.accountNum" controls-position="right" :min="1" size="mini" style="width: 80px;" /><span class="label">{{ $t('号') }}</span>
            </span>
            <span>
              <span class="label">{{ $t('日期') }}</span>
              <el-date-picker v-model="voucher.accountDate" value-format="yyyy-MM-dd" type="date" :picker-options="pickTime" size="mini" style="width: 145px;" />
            </span>
          </div>
          <div>
            <span class="label">{{ $t('附单据') }}</span><el-input-number v-model="voucher.documentNum" controls-position="right" :min="0" size="mini" style="width: 80px;" /><span class="label">{{ $t('张') }}</span>
            <span class="ml10 link-type">
              <el-popover
                placement="left"
                width="400"
                trigger="click"
                @hide="updateRemark"
              >
                <el-input v-model="voucher.remark" type="textarea" :autosize="{ minRows: 1, maxRows: 4}" :placeholder="$t('备注')" maxlength="2000" />
                <el-button slot="reference" type="text">备注</el-button>
              </el-popover>
            </span>
          </div>
        </div>
        <table class="charge-table edit-charge-table" border="1">
          <tr>
            <td width="5%">操作</td>
            <td width="22%">摘要</td>
            <td width="23%">会计科目</td>
            <td width="50%">
              <table style="height: 50px;">
                <tr style="border-bottom: 1px solid #dadada;">
                  <td width="50%" style="border-right: 1px solid #dadada;">借方金额</td>
                  <td width="50%">贷方金额</td>
                </tr>
                <tr>
                  <td style="border-right: 1px solid #dadada;">
                    <table class="debtor-lender-table" style="height: 100%;">
                      <tr>
                        <td>亿</td>
                        <td>千</td>
                        <td>百</td>
                        <td>十</td>
                        <td>万</td>
                        <td>千</td>
                        <td>百</td>
                        <td>十</td>
                        <td>元</td>
                        <td>角</td>
                        <td>分</td>
                      </tr>
                    </table>
                  </td>
                  <td>
                    <table class="debtor-lender-table" style="height: 100%;">
                      <tr>
                        <td>亿</td>
                        <td>千</td>
                        <td>百</td>
                        <td>十</td>
                        <td>万</td>
                        <td>千</td>
                        <td>百</td>
                        <td>十</td>
                        <td>元</td>
                        <td>角</td>
                        <td>分</td>
                      </tr>
                    </table>
                  </td>
                </tr>
              </table>
            </td>
          </tr>
          <tr v-for="(item,index) in list" :key="index">
            <td>
              <div class="charge-table-icon" @click="addList">
                <i class="el-icon-circle-plus" />
              </div>
              <div class="charge-table-icon" @click="removeList(index)">
                <i class="el-icon-remove" />
              </div>
            </td>
            <td class="td-main">
              <!-- 摘要 -->
              <div v-if="!item.isShowMainInput" class="main-subject" @click="showInput(index,'main')">
                {{ item.main }}
              </div>
              <div v-if="item.isShowMainInput" class="main-subject main-input">
                <!--              <el-input v-model="item.main" size="mini" clearable @change="hideInput(index,'main')" />-->
                <!-- <el-autocomplete
                  v-model="item.main"
                  class="inline-input"
                  :fetch-suggestions="querySearch"
                  placeholder="请输入内容"
                  @select="handleSelect"
                  @change="hideInput(index,'main')"
                /> -->
                <textarea v-model="item.main" v-focus @blur="hideInput(index,'main')" @keydown="handlePushKeyword($event)" />

                <div class="dropdown-menu suggest-list special-elements" style="top: 60px;">
                  <ul class="item-list">
                    <li
                      v-for="ele in abstractContentList"
                      :key="ele.value"
                      :class="ele.value === item.main ? 'hover' : '' "
                      @click="voluationInput(index,ele)"
                    >
                      {{ ele.value }}
                    </li>
                  </ul>
                </div>
              </div>
            </td>
            <td>
              <!-- 科目 -->
              <div v-if="!item.isShowSubjectInput" class="main-subject" @click="showInput(index,'subject')">
                {{ item.subject.name }}<span v-for="v in item.auxiliaryOption" :key="v.field">{{ item.subject[v.field] ? ' - ' + item.subject[v.field] : '' }}</span>
              </div>
              <div v-if="item.isShowSubjectInput" class="main-subject main-subject-input">
                <div>
                  <el-select
                    v-model="item.subject.id"
                    size="mini"
                    style="width:100%;"
                    filterable
                    clearable
                    @change="hideInput(index,'subject')"
                  >
                    <el-option
                      v-for="ele in fundAccountSubjectList"
                      :key="ele.subjectCode"
                      :label="ele.subjectCode + ' ' +ele.subjectName"
                      :value="ele.subjectCode"
                    />
                  </el-select>
                  <!-- 辅助核算 -->
                  <template v-if="item.isAuxiliary">
                    <div v-for="(el, auxiliaryIndex) in item.auxiliaryOption" :key="el.field + 'Id'" class="mt5 auxiliaryDiv">
                      <span>{{ el.placeholder }}</span>
                      <el-select
                        v-model="item.subject[el.field + 'Id']"
                        size="mini"
                        style="width:100%;"
                        clearable
                        filterable
                        :placeholder="el.placeholder"
                        @change="hideInput(index,'auxiliary', auxiliaryIndex)"
                      >
                        <el-option
                          v-for="ele in el.list"
                          :key="ele.id"
                          :label="ele.name"
                          :value="ele.id"
                        />
                      </el-select>
                    </div>
                  </template>
                </div>
              <!-- <i class="el-icon-check link-type" @click="item.isShowSubjectInput = false" /> -->
              </div>
            </td>
            <td>
              <table>
                <tr>
                  <td width="50%" style="border-right: 1px solid #dadada;">
                    <table class="debtor-tbale debtor-lender-table">
                      <tr
                        v-if="!item.isShowDebtorInput"
                        @click="showInput(index,'debtor')"
                      >
                        <td v-for="debtor in item.debtorList" :key="debtor + getUuid()" class="bold" :class="item.debtor < 0 ? 'red' : ''">{{ debtor }}</td>
                      </tr>

                      <tr v-if="item.isShowDebtorInput" class="pad5">
                        <!-- 借方 -->

                        <Money
                          v-model="item.debtor"
                          size="mini"
                          @blur="hideInput(index,'debtor')"
                          @change="hideInput(index,'debtor')"
                        />
                      </tr>
                    </table>
                  </td>
                  <td width="50%">
                    <table class="lender-tbale debtor-lender-table">
                      <tr
                        v-if="!item.isShowLenderInput"
                        @click="showInput(index,'lender')"
                      >
                        <td v-for="lender in item.lenderList" :key="lender + getUuid()" class="bold" :class="item.lender < 0 ? 'red' : ''">{{ lender }}</td>
                      </tr>

                      <tr v-if="item.isShowLenderInput" class="pad5">
                        <!-- 贷方 -->

                        <Money
                          v-model="item.lender"
                          size="mini"
                          @blur="hideInput(index,'lender')"
                          @change="hideInput(index,'lender')"
                        />
                      </tr>
                    </table>
                  </td>
                </tr>
              </table>
            </td>
          </tr>
          <tr>
            <td colspan="3" style="text-align: left;padding-left: 10px;line-height: 50px;">合计：{{ amountTotal }}</td>
            <td>
              <table>
                <tr>
                  <td width="50%" style="border-right: 1px solid #dadada;">
                    <table class="debtor-tbale debtor-lender-table">
                      <tr>
                        <td v-for="(debtor, ind) in debtorTotalList" :key="ind + getUuid()" class="bold" :class="borrowAmount < 0 ? 'red' : ''">{{ debtor }}</td>
                      </tr>
                    </table>
                  </td>
                  <td width="50%">
                    <table class="lender-tbale debtor-lender-table">
                      <tr>
                        <td v-for="(lender, ind) in lenderTotalList" :key="ind + getUuid()" class="bold" :class="loanAmount < 0 ? 'red' : ''">{{ lender }}</td>
                      </tr>
                    </table>
                  </td>
                </tr>
              </table>
            </td>
          </tr>
        </table>
        <div style="height: 50px;line-height: 50px;">制单人: {{ voucher.creatorName }}</div>
      </div>
    </div>
    <div ref="print" class="is-print" style="display: none;">
      <h1 class="charge-title">{{ $t('记账凭证') }}</h1>
      <div class="charge">
        <div class="display-between">
          <div class="gap10">
            <!-- <span>单位:  -</span> -->
            <span>日期: {{ voucher.accountDate }}</span>
          </div>
          <div>凭证号: {{ formatVoucherWordId(voucher.voucherWordId) }}-{{ voucher.accountNum }}</div>
        </div>
        <table class="print-charge-table" border="1">
          <tr>
            <th width="25%">摘要</th>
            <th width="35%">会计科目</th>
            <th width="20%">借方金额</th>
            <th width="20%">贷方金额</th>
          </tr>
          <tr v-for="(item,index) in list" :key="index + getUuid()">
            <td class="align-left">
              <div>{{ item.main }}</div>
            </td>
            <td class="align-left">
              <div>{{ item.subject.name }}<span v-for="v in item.auxiliaryOption" :key="v.field">{{ item.subject[v.field] ? ' - ' + item.subject[v.field] : '' }}</span></div>
            </td>
            <td class="align-right">
              <div>{{ item.debtor ? moneyFormat(item.debtor) : '' }}</div>
            </td>
            <td class="align-right">
              <div>{{ item.lender ? moneyFormat(item.lender) : '' }}</div>
            </td>
          </tr>
          <tr>
            <td colspan="2" class="align-left">
              <div>合计：{{ amountTotal }}</div>
            </td>
            <td class="align-right">
              <div>{{ borrowAmount ? moneyFormat(borrowAmount) : '' }}</div>
            </td>
            <td class="align-right">
              <div>{{ loanAmount ? moneyFormat(loanAmount) : '' }}</div>
            </td>
          </tr>
        </table>
        <div style="height: 50px;line-height: 50px;">制单人: {{ voucher.creatorName }}</div>
      </div>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
Vue.directive('focus', {
  inserted: function(el) {
    el.focus()
  }
})
import { getFundAccountYearMonthList } from '@/api/fin/fundAccount/finFundAccount'
import { listFinVoucherWord } from '@/api/fin/voucherWord/finVoucherWord'
import {
  getAuxiliaryOptionList,
  getFundAccountSubjectList
} from '@/api/fin/fundAccount/finFundAccountDetail'
import {
  getAccountNum,
  getFinAuxiliaryAccounting,
  saveFinAuxiliaryAccounting, updateRemarkInVoucher
} from '@/api/fin/auxiliaryAccounting/finAuxiliaryAccounting'
import { getUser } from '@/api/system/user'
import { getAbstractContentList } from '@/api/fin/auxiliaryAccounting/finAuxiliaryAccountingDetail'
import { mapActions, mapState } from 'vuex'

  export default {
    name: 'VoucherForm',
    props: {
      operateType: {
        type: String,
        default: () => ''
      }
    },
    data() {
      return {
        voucher: {
          fundAccountId: undefined,
          voucherWordId: undefined,
          accountNum: undefined,
          yearMonth: undefined,
          carryoverRecordId: undefined,
          accountDate: undefined,
          documentNum: 0,
          borrowAmount: undefined, // 借方金额合计
          loanAmount: undefined, // 贷方金额合计
          creator: undefined,
          creatorName: undefined
        },
        list: [],
        borrowAmount: 0,
        operateHandle: 'add',
        saveAndInsertLabel: '保存并新增',
        btnHandleLabel: '',
        debtorTotalList: [],
        loanAmount: 0,
        lenderTotalList: [],
        abstractContentList: [],
        abstractContentInitList: [],
        mainStrList: [],
        finFundAccountList: [], // 基金账套列表
        finVoucherWordList: [], // 凭证字列表
        fundAccountSubjectList: [] // 基金账套科目详情列表
      }
    },
    computed: {
      ...mapState('finReport', ['finQueryParams']),
      amountTotal() {
        // var total = this.borrowAmount + this.loanAmount
        var total = this.borrowAmount
        return this.toChineseAmount(total)
      },
      pickTime() {
        var that = this
        return {
          disabledDate(time) {
            var yearMonthTime = that.voucher.yearMonth.replaceAll('年', '-').replace('月', '-') + '01 00:00:00'
            return time.getTime() < new Date(yearMonthTime)
          }
        }
      }
    },
    mounted() {
      if (this.operateType !== 'insert') {
        const data = {
          operateHandle: 'new'
        }
        this.insertData(data)
      }
    },
    updated() {
      // 给特定区域添加ID   绑定onmousedown 事件
      var chargeContainer = document.getElementById('chargeContainer')
      var outDiv = chargeContainer.getElementsByClassName('special-elements')
      for (var i = 0; i < outDiv.length; i++) {
        outDiv[i].onmousedown = function(e) {
          if (e && e.preventDefault) { // 现代浏览器阻止默认事件
            e.preventDefault()
          } else { // IE阻止默认事件
            window.event.returnValue = false
          }
          return false
        }
      }
    },
  methods: {
      ...mapActions('finReport', ['changeQueryParams']),
      handlePushKeyword(event) {
        if (event.keyCode === 13) {
          event.preventDefault() // 阻止浏览器默认换行操作
          return false
        }
      },
      voluationInput(index, val) {
        this.list[index].main = val.value
        this.list[index].isShowMainInput = false
      },
      getUuid() {
        function S4() {
          return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
        }
        return (S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4())
      },
      insertData(data) {
        // 直接添加页面入口
        if (data.operateHandle === 'new') {
          this.initFormData()
          // 获取基金账套列表
          this.getFundAccountList()
          // 获取凭证字列表
          this.getVoucherWordList()
        } else if (data.operateHandle === 'insert') {
          // 获取基金账套列表
          getFundAccountYearMonthList({}).then(response => {
            this.finFundAccountList = response.data
          })
          const paramData = {
            fundAccountId: data.fundAccountId
          }
          getFundAccountSubjectList(paramData).then(response => {
            this.fundAccountSubjectList = response.data
          })
          this.voucher.accountDate = this.getLastDayOfMonthFromString(data.yearMonthStr)
          listFinVoucherWord({}).then(response => {
            this.finVoucherWordList = response.rows
          })
          // 获取凭证字列表
          this.getVoucherWordList()
          this.$nextTick(() => {
            this.operateHandle = 'insert'
            this.$set(this, 'voucher', {
              fundAccountId: data.fundAccountId,
              voucherWordId: data.voucherWordId,
              accountNum: data.accountNum,
              yearMonth: data.yearMonthStr,
              carryoverRecordId: data.carryoverRecordId,
              accountDate: data.accountDate,
              documentNum: 0,
              borrowAmount: undefined, // 借方金额合计
              loanAmount: undefined, // 贷方金额合计
              creator: this.$store.state.user.userId,
              creatorName: ''
            })
            getUser(this.$store.state.user.userId).then(response => {
              this.$set(this.voucher, 'creatorName', response.data.nickName)
            })
            this.list = []
            for (let i = 0; i < 4; i++) {
              const data = {
                main: '',
                isShowMainInput: false,
                auxiliaryOption: [],
                subject: {
                  name: '',
                  deal: '',
                  dealId: '',
                  cashId: '',
                  cash: ''
                },
                isShowSubjectInput: false,
                debtor: '',
                debtorList: ['', '', '', '', '', '', '', '', '', '', ''],
                isShowDebtorInput: false,
                lender: '',
                lenderList: ['', '', '', '', '', '', '', '', '', '', ''],
                isShowLenderInput: false
              }
              this.list.push(data)
            }
            this.borrowAmount = 0
            this.debtorTotalList = ['', '', '', '', '', '', '', '', '', '', '']
            this.loanAmount = 0
            this.lenderTotalList = ['', '', '', '', '', '', '', '', '', '', '']
          })
        }
      },
      // querySearch(queryString, cb) {
      //   var abstractContentList = this.abstractContentList
      //   var results = queryString ? abstractContentList.filter(this.createFilter(queryString)) : abstractContentList
      //   // 调用 callback 返回建议列表的数据
      //   cb(results)
      // },
      // createFilter(queryString) {
      //   return (abstractContentList) => {
      //     return (abstractContentList.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      //   }
      // },
      handleSelect(item) {
        this.$forceUpdate()
        console.log(item)
      },
      doPrint() {
        this.$print(this.$refs.print)
      },
      formatVoucherWordId(id) {
        var item = this.finVoucherWordList.find(ele => ele.id === id)
        if (item) {
          return item.voucherWord
        }
      },
      // 根据基金账套
      getSubjectList(fundAccountId) {
        if (fundAccountId === null || fundAccountId === undefined || fundAccountId === '') {
          return
        }
        if (this.finFundAccountList && this.finFundAccountList.length > 0) {
          this.finFundAccountList.forEach(item => {
            if (fundAccountId === item.id) {
              this.voucher.carryoverRecordId = item.carryoverRecordId
              this.voucher.yearMonth = item.yearMonth
            }
          })
        }
        const paramData = {
          fundAccountId: fundAccountId
        }
        getFundAccountSubjectList(paramData).then(response => {
          this.fundAccountSubjectList = response.data
        })
        getAbstractContentList(paramData).then(response => {
          this.abstractContentList = JSON.parse(JSON.stringify(response.data)) || []
          this.abstractContentInitList = JSON.parse(JSON.stringify(response.data)) || []
          this.mainStrList = []
          if (this.abstractContentInitList.length > 0) {
            this.mainStrList = this.abstractContentInitList.map(v => v.value)
          }
        })
        this.voucher.accountDate = this.getLastDayOfMonthFromString(this.voucher.yearMonth)
        const param = {
          fundAccountId: fundAccountId,
          yearMonth: this.voucher.carryoverRecordId
        }
        console.log('param', param)
        this.changeQueryParams(param)
        this.$forceUpdate()
      },
      // 获取基金账套列表
      getFundAccountList() {
        getFundAccountYearMonthList({}).then(response => {
          this.finFundAccountList = response.data
          if (this.finFundAccountList && this.finFundAccountList.length > 0) {
            var item = this.finFundAccountList[0]
            this.voucher.fundAccountId = item.id
            this.voucher.carryoverRecordId = item.carryoverRecordId
            this.voucher.yearMonth = item.yearMonth
            if (this.finQueryParams.accountId && this.finQueryParams.yearMonth) {
              this.finFundAccountList.forEach(data => {
                if (data.id === this.finQueryParams.accountId) {
                  item = data
                  this.voucher.fundAccountId = data.id
                  this.voucher.carryoverRecordId = data.carryoverRecordId
                  this.voucher.yearMonth = data.yearMonth
                  console.log('hskdskj', data.id, data.carryoverRecordId)
                }
              })
            }
            // 初始化加载默认账套时，查询科目
            this.getSubjectList(item.id)
            // 获取凭证账套号
            this.getVoucherNum(this.voucher.fundAccountId, this.voucher.carryoverRecordId, this.voucher.voucherWordId)
          }
        })
      },
      // 获取凭证账套号
      getAccountNum(voucherWordId) {
        this.getVoucherNum(this.voucher.fundAccountId, this.voucher.carryoverRecordId, voucherWordId)
      },
      // 获取凭证账套号
      getVoucherNum(fundAccountId, carryoverRecordId, voucherWordId) {
        const numData = {
          fundAccountId: fundAccountId,
          carryoverRecordId: carryoverRecordId,
          voucherWordId: voucherWordId
        }
        getAccountNum(numData).then(response => {
          this.voucher.accountNum = response.data
        })
      },
      // 根据科目获取辅助核算列表
      setAuxiliaryOption(row, index) {
        const param = {
          fundId: row.fundId,
          fundAccountId: row.fundAccountId,
          auxiliaryAccounting: row.auxiliaryAccounting
        }
        getAuxiliaryOptionList(param).then(response => {
          this.list[index].auxiliaryOption = response.data
        })
      },
      // 获取凭证字列表
      getVoucherWordList() {
        listFinVoucherWord({}).then(response => {
          this.finVoucherWordList = response.rows
          // 初始化把凭证字列表中的默认赋值
          if (this.finVoucherWordList && this.finVoucherWordList.length > 0) {
            this.finVoucherWordList.forEach(item => {
              if (item.whetherDefault === 'Y') {
                this.voucher.voucherWordId = item.id
              }
            })
          }
        })
      },
      showInput(index, type) {
        this.list.forEach((v, i) => {
          v.isShowDebtorInput = false
          v.isShowLenderInput = false
          v.isShowMainInput = false
          v.isShowSubjectInput = false
          if (i === index && type === 'debtor') {
            this.list[index].isShowDebtorInput = true
          } else if (i === index && type === 'lender') {
            this.list[index].isShowLenderInput = true
          } else if (i === index && type === 'main') {
            this.list[index].isShowMainInput = true
            if (index > 0 && !this.list[index].main) {
              this.list[index].main = this.list[index - 1].main
            }
          } else if (i === index && type === 'subject') {
            this.list[index].isShowSubjectInput = true
            this.list[index].isAuxiliary = true
          }
        })
        this.$forceUpdate()
      },
      // 根据列表摘要添加到摘要筛选列表
      addMainList(val, index) {
        // 先进行初始化数据，这里先把默认的给加载
        this.abstractContentList = JSON.parse(JSON.stringify(this.abstractContentInitList))
        this.mainStrList = []
        this.abstractContentList.forEach(item => {
          this.mainStrList.push(item.value)
        })
        // 循环列表，但是排序当前的索引的 this.list
        this.list.forEach((item, i) => {
          if (index !== i) {
            if (!this.mainStrList.includes(item.main) && item.main) {
              this.mainStrList.push(item.main)
              const data = {
                label: item.main,
                value: item.main
              }
              this.abstractContentList.unshift(data)
            }
          }
        })
        if (!this.mainStrList.includes(val) && val) {
          this.mainStrList.push(val)
          const data = {
            label: val,
            value: val
          }
          this.abstractContentList.unshift(data)
        }
        this.list[index].isShowMainInput = false
        this.$forceUpdate()
      },
      hideInput(index, type, auxiliaryIndex) {
        if (type === 'debtor') { // 借方
          var debtor = this.list[index].debtor + ''
          var inx = debtor.indexOf('.')
          if (inx !== -1 && debtor.length - 1 !== inx) {
            this.list[index].debtor = (this.list[index].debtor * 1).toFixed(4)
          }
          this.list[index].isShowDebtorInput = false
          if (debtor) {
            var debtorList = ['', '', '', '', '', '', '', '', '', '', '']
            this.list[index].debtorList = this.collatingData(debtor, debtorList)
            this.list[index].lender = 0
            this.list[index].lenderList = ['', '', '', '', '', '', '', '', '', '', '']
            this.calcLenderTotal(index)
          } else {
            this.list[index].debtorList = ['', '', '', '', '', '', '', '', '', '', '']
          }
          this.calcDebtorTotal(index)
        } else if (type === 'lender') { // 贷方
          var lender = this.list[index].lender + ''
          var _inx = lender.indexOf('.')
          if (_inx !== -1 && lender.length - 1 !== _inx) {
            this.list[index].lender = (this.list[index].lender * 1).toFixed(4)
          }
          this.list[index].isShowLenderInput = false
          if (lender) {
            var lenderList = ['', '', '', '', '', '', '', '', '', '', '']
            this.list[index].lenderList = this.collatingData(lender, lenderList)
            this.list[index].debtor = 0
            this.list[index].debtorList = ['', '', '', '', '', '', '', '', '', '', '']
            this.calcDebtorTotal(index)
          } else {
            this.list[index].lenderList = ['', '', '', '', '', '', '', '', '', '', '']
          }
          this.calcLenderTotal(index)
        } else if (type === 'main') { // 摘要
          this.list[index].isShowMainInput = false
          this.addMainList(this.list[index].main, index)
        } else if (type === 'subject') { // 科目
          // this.list[index].isShowSubjectInput = false
          var row = this.fundAccountSubjectList.find(v => v.subjectCode === this.list[index].subject.id)
          if (row) {
            this.list[index].subject.name = row.subjectName
            if (row.auxiliaryAccounting && row.auxiliaryAccounting.length > 0) {
              this.setAuxiliaryOption(row, index)
              this.list[index].isAuxiliary = true
            } else {
              this.list[index].isAuxiliary = false
              this.list[index].auxiliaryOption.forEach(el => {
                this.list[index].subject[el.field] = ''
                this.list[index].subject[el.field + 'Id'] = ''
              })
              this.list[index].isShowSubjectInput = false
            }
          }
          if (auxiliaryIndex === this.list[index].auxiliaryOption.length - 1) {
            this.list[index].isShowSubjectInput = false
          }
        } else if (type === 'auxiliary') { // 科目
          // this.list[index].isShowSubjectInput = false
          var auxiliary = this.list[index].auxiliaryOption[auxiliaryIndex]
          if (auxiliary) {
            if (auxiliary.list && auxiliary.list.length > 0) {
              auxiliary.list.forEach(el => {
                if (el.id === this.list[index].subject[auxiliary.field + 'Id']) {
                  this.list[index].subject[auxiliary.field] = el.name
                }
              })
              this.list[index].isAuxiliary = true
            }
          }
          if (auxiliaryIndex === this.list[index].auxiliaryOption.length - 1) {
            this.list[index].isShowSubjectInput = false
          }
        }
      },
      calcDebtorTotal(index) {
        var borrowAmount = 0
        for (var i in this.list) {
          if (this.list[i].debtor !== null && this.list[i].debtor !== '') {
            if (!(index && index === i)) {
              borrowAmount += (this.list[i].debtor) * 1
            }
          }
        }
        var debtorTotalList = ['', '', '', '', '', '', '', '', '', '', '']
        if (borrowAmount === 0) {
          this.borrowAmount = 0
          this.debtorTotalList = debtorTotalList
        } else {
          this.borrowAmount = parseFloat(borrowAmount.toFixed(2))
          this.debtorTotalList = this.collatingData(borrowAmount, debtorTotalList)
        }
        this.$forceUpdate()
      },
      calcLenderTotal(index) {
        var loanAmount = 0
        for (var i in this.list) {
          if (this.list[i].lender !== null && this.list[i].lender !== '') {
            if (!(index && index === i)) {
              loanAmount += (this.list[i].lender) * 1
            }
          }
        }
        var lenderTotalList = ['', '', '', '', '', '', '', '', '', '', '']
        if (loanAmount === 0) {
          this.loanAmount = 0
          this.lenderTotalList = lenderTotalList
        } else {
          this.loanAmount = parseFloat(loanAmount.toFixed(2))
          this.lenderTotalList = this.collatingData(loanAmount, lenderTotalList)
        }
        this.$forceUpdate()
      },
      collatingData(value, list) {
        value = value + ''
        if (value.indexOf('-') !== -1) {
          value = value.replace(/-/g, '')
        }
        if (value.indexOf('.') !== -1) {
          value = (value * 1).toFixed(2)
          value = (value + '').replace(/\./g, '')
        } else {
          if (value && parseFloat(value) > 0) {
            value = value + '00'
          } else {
            value = value + ''
          }
        }
        if (value.length <= 11) {
          var cha = list.length - value.length
          for (var i = 0; i < value.length; i++) {
            list[i + cha] = value.charAt(i)
          }
        } else {
          // eslint-disable-next-line no-redeclare
          for (var i = 0; i < value.length; i++) {
            list[i] = value.charAt(i)
          }
        }
        return list
      },
      formatDate(fmt, date) {
        if (typeof date === 'string') {
          date = new Date(date)
        }
        var o = {
          'M+': date.getMonth() + 1, // 月份
          'd+': date.getDate(), // 日
          'h+': date.getHours(), // 小时
          'm+': date.getMinutes(), // 分
          's+': date.getSeconds(), // 秒
          'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
          'S': date.getMilliseconds() // 毫秒
        }
        if (/(y+)/.test(fmt)) { fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length)) }
        for (var k in o) {
            if (new RegExp('(' + k + ')').test(fmt)) {
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
            }
        }
        return fmt
      },
      formatNum(val) {
        if (val !== undefined && val !== null && val !== '' && !isNaN(val)) {
          if (Number(val)) {
            var result = parseFloat(val)
            if (result > 999000000000000) {
              this.msgError(this.$t('警告，金额不能大于等于千万亿！'))
              return 0
            }
            return result
          } else {
            return 0
          }
        } else {
          return 0
        }
      },
      // 更新备注功能
      updateRemark() {
        if (this.voucher.id !== null && this.voucher.id !== undefined && this.voucher.id !== '') {
          const data = {
            id: this.voucher.id,
            remark: this.voucher.remark
          }
          updateRemarkInVoucher(data)
        }
      },
      getYearMonthLabel(str) {
        if (str.indexOf('月') !== -1) {
          str.replace('-', '年')
        } else {
          return str.replace('-', '年') + '月'
        }
      },
      // 初始化数据
      init(data) {
        this.initFormData()
        // 获取基金账套列表
        getFundAccountYearMonthList({}).then(response => {
          this.finFundAccountList = response.data
        })
        // 获取凭证字列表
        listFinVoucherWord({}).then(response => {
          this.finVoucherWordList = response.rows
        })
        this.loading = true
        this.operateHandle = 'edit'
        if (data != null && data.id !== undefined) {
          getFinAuxiliaryAccounting(data.id).then(response => {
            this.voucher = response.data
            const paramData = {
              fundAccountId: this.voucher.fundAccountId
            }
            getFundAccountSubjectList(paramData).then(response => {
              this.fundAccountSubjectList = response.data
            })
            getAbstractContentList(paramData).then(response => {
              this.abstractContentList = JSON.parse(JSON.stringify(response.data)) || []
              this.abstractContentInitList = JSON.parse(JSON.stringify(response.data)) || []
              this.mainStrList = []
              if (this.abstractContentInitList.length > 0) {
                this.mainStrList = this.abstractContentInitList.map(v => v.value)
              }
            })
            this.$set(this.voucher, 'yearMonth', this.getYearMonthLabel(data.yearMonth))
            this.borrowAmount = this.voucher.borrowAmount
            this.amountTotal = this.voucher.amountTotal
            var debtorTotalList = ['', '', '', '', '', '', '', '', '', '', '']
            var lenderTotalList = ['', '', '', '', '', '', '', '', '', '', '']
            this.debtorTotalList = this.collatingData(this.borrowAmount, debtorTotalList)
            this.loanAmount = this.voucher.loanAmount
            this.lenderTotalList = this.collatingData(this.loanAmount, lenderTotalList)
            this.list = []
              response.data.detailList.forEach(item => {
                var debtorItemList = ['', '', '', '', '', '', '', '', '', '', '']
                var lenderItemList = ['', '', '', '', '', '', '', '', '', '', '']
                const data = {
                  main: item.abstractContent,
                  id: item.id,
                  isShowMainInput: false,
                  auxiliaryOption: item.auxiliaryOption,
                  subject: {
                    name: item.subjectName,
                    deal: item.dealName,
                    dealId: item.dealId,
                    cashId: item.cashId,
                    cash: item.cashName,
                    id: item.subjectCode
                  },
                  isShowSubjectInput: false,
                  debtor: item.borrowAmount,
                  debtorList: item.borrowAmount ? this.collatingData(item.borrowAmount, debtorItemList) : debtorItemList,
                  isShowDebtorInput: false,
                  lender: item.loanAmount,
                  lenderList: item.loanAmount ? this.collatingData(item.loanAmount, lenderItemList) : lenderItemList,
                  isShowLenderInput: false
                }
                this.list.push(data)
              })
            this.loading = false
          }).catch(() => {
            this.loading = false
          })
        }
      },
      // 获取最后一天日期
      getLastDayOfMonthFromString(dateString) {
        // 解析日期字符串为Date对象
        var parts = dateString.split('年')
        var year = parseInt(parts[0], 10)
        var month = parseInt(parts[1].split('月')[0], 10) - 1 // 月份需要减1，因为JavaScript的月份是从0开始的
        var date = new Date(year, month, 1) // 设置日期为月份的第一天
        // 设置日期为月份的最后一天
        date.setMonth(date.getMonth() + 1, 0)
        // 格式化日期为字符串
        var lastDayOfMonth = ''
        if ((date.getMonth() + 1) > 9) {
           lastDayOfMonth = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate()
        } else {
           lastDayOfMonth = date.getFullYear() + '-0' + (date.getMonth() + 1) + '-' + date.getDate()
        }
        return lastDayOfMonth
      },
      // 初始化数据
      copyInit(data) {
        this.initFormData()
        // 获取基金账套列表
        getFundAccountYearMonthList({}).then(response => {
          this.finFundAccountList = response.data
        })
        // 获取凭证字列表
        listFinVoucherWord({}).then(response => {
          this.finVoucherWordList = response.rows
        })
        this.operateHandle = 'copy'
        this.loading = true
        if (data != null && data.id !== undefined) {
          getFinAuxiliaryAccounting(data.id).then(response => {
            this.voucher = response.data
            this.getSubjectList(response.data.fundAccountId)
            this.getVoucherNum(this.voucher.fundAccountId, this.voucher.carryoverRecordId, this.voucher.voucherWordId)
            this.voucher.id = undefined
            this.borrowAmount = this.voucher.borrowAmount
            this.amountTotal = this.voucher.amountTotal
            var debtorTotalList = ['', '', '', '', '', '', '', '', '', '', '']
            var lenderTotalList = ['', '', '', '', '', '', '', '', '', '', '']
            this.debtorTotalList = this.collatingData(this.borrowAmount, debtorTotalList)
            this.loanAmount = this.voucher.loanAmount
            this.lenderTotalList = this.collatingData(this.loanAmount, lenderTotalList)
            this.list = []
            response.data.detailList.forEach(item => {
              var debtorItemList = ['', '', '', '', '', '', '', '', '', '', '']
              var lenderItemList = ['', '', '', '', '', '', '', '', '', '', '']
              const data = {
                main: item.abstractContent,
                isShowMainInput: false,
                auxiliaryOption: item.auxiliaryOption,
                subject: {
                  name: item.subjectName,
                  deal: item.dealName,
                  dealId: item.dealId,
                  cashId: item.cashId,
                  cash: item.cashName,
                  id: item.subjectCode
                },
                isShowSubjectInput: false,
                debtor: item.borrowAmount,
                debtorList: item.borrowAmount ? this.collatingData(item.borrowAmount, debtorItemList) : debtorItemList,
                isShowDebtorInput: false,
                lender: item.loanAmount,
                lenderList: item.loanAmount ? this.collatingData(item.loanAmount, lenderItemList) : lenderItemList,
                isShowLenderInput: false
              }
              this.list.push(data)
            })
            this.loading = false
          }).catch(() => {
            this.loading = false
          })
        }
      },
      initFormData() {
        this.voucher = {
          voucherWordId: '',
          fundAccountId: '',
          accountNum: undefined,
          yearMonth: '',
          carryoverRecordId: '',
          accountDate: undefined,
          documentNum: 0,
          borrowAmount: undefined, // 借方金额合计
          loanAmount: undefined, // 贷方金额合计
          creator: this.$store.state.user.userId,
          creatorName: ''
        }
        getUser(this.$store.state.user.userId).then(response => {
          this.$set(this.voucher, 'creatorName', response.data.nickName)
        })
        this.list = []
        for (let i = 0; i < 4; i++) {
          const data = {
            main: '',
            id: undefined,
            isShowMainInput: false,
            auxiliaryOption: [],
            subject: {
              name: '',
              deal: '',
              dealId: '',
              cashId: '',
              cash: ''
            },
            isShowSubjectInput: false,
            debtor: '',
            debtorList: ['', '', '', '', '', '', '', '', '', '', ''],
            isShowDebtorInput: false,
            lender: '',
            lenderList: ['', '', '', '', '', '', '', '', '', '', ''],
            isShowLenderInput: false
          }
          this.list.push(data)
        }
        this.borrowAmount = 0
        this.debtorTotalList = ['', '', '', '', '', '', '', '', '', '', '']
        this.loanAmount = 0
        this.lenderTotalList = ['', '', '', '', '', '', '', '', '', '', '']
      },
      addList() {
        var obj = {
          main: '',
          isShowMainInput: false,
          auxiliaryOption: [],
          subject: {
            name: '',
            deal: '',
            dealId: '',
            cashId: '',
            cash: '',
            id: ''
          },
          isShowSubjectInput: false,
          debtor: '',
          debtorList: ['', '', '', '', '', '', '', '', '', '', ''],
          isShowDebtorInput: false,
          lender: '',
          lenderList: ['', '', '', '', '', '', '', '', '', '', ''],
          isShowLenderInput: false
        }
        this.list.push(obj)
      },
      removeList(index) {
        if (this.list.length <= 2) {
          this.$message.error('至少保存两行')
          return
        }
        this.list.splice(index, 1)
        this.calcDebtorTotal()
        this.calcLenderTotal()
      },
      onSubmitAndInsert() {
        this.btnHandleLabel = '新增'
        var reqObj = this.checkListData()
        if (reqObj) {
          this.submitForm()
        }
      },
      onSubmit() {
        this.saveAndInsertLabel = '新增'
        this.btnHandleLabel = '保存'
        var reqObj = this.checkListData()
        if (reqObj) {
          this.submitForm()
        }
      },
      checkListData() {
        var checkFlag = true
        var validDataCount = 0
        if ((this.borrowAmount !== 0 || this.loanAmount !== 0) && this.loanAmount * 1 !== this.borrowAmount * 1) {
          this.$message.error('凭证借贷不平衡，请检查')
          return false
        }
        for (var i in this.list) {
          if (!this.list[i].main && !this.list[i].subject.name && !this.list[i].debtor && !this.list[i].lender) {
            validDataCount++
          } else {
            if (!this.list[i].main) {
              this.$message.error('第' + (i * 1 + 1) + '行中的摘要为必填项，请填写了再提交')
              return false
            }
            if (this.list[i].subject.name === null || this.list[i].subject.name === '') {
              this.$message.error('第' + (i * 1 + 1) + '行中的会计科目为必填项，请填写了再提交')
              return false
            }
            if (this.list[i].debtor && this.list[i].lender) {
              this.$message.error('第' + (i * 1 + 1) + '行中借方金额、贷方金额只能填一个，请重新填写后再提交')
              return false
            }
            if ((this.list[i].debtor === null || this.list[i].debtor === '') && (this.list[i].lender === null || this.list[i].lender === '')) {
              this.$message.error('第' + (i * 1 + 1) + '行中借方金额、贷方金额必须填一个，请填写了再提交')
              return false
            }
          }
        }
        if (this.list.length - validDataCount < 2) {
          this.$message.error('至少添加两行有效数据')
          return false
        }
        return checkFlag
      },
      /** 提交按钮 */
      submitForm() {
        this.loading = true
        this.voucher.loanAmount = this.loanAmount
        this.voucher.borrowAmount = this.borrowAmount
        this.voucher.amountTotal = this.amountTotal
        this.voucher.operateHandle = this.operateHandle
        this.voucher.detailList = []
        this.list.forEach(item => {
          if ((item.main && item.subject.id && item.debtor) || (item.main && item.subject.id && item.lender)) {
            const row = {
              id: item.id,
              subjectCode: item.subject.id,
              abstractContent: item.main,
              borrowAmount: item.debtor,
              loanAmount: item.lender,
              dealId: item.subject.dealId,
              cashId: item.subject.cashId
            }
            this.voucher.detailList.push(row)
          }
        })
        var fundAccountId = this.voucher.fundAccountId
        var voucherWordId = this.voucher.voucherWordId
        var accountNum = this.voucher.accountNum + 1
        var yearMonth = this.voucher.yearMonth
        var accountDate = this.voucher.accountDate
        var carryoverRecordId = this.voucher.carryoverRecordId
        saveFinAuxiliaryAccounting(this.voucher).then(response => {
          if (response.code === 200) {
            // 防止多次保存，出现多条数据
            if (this.btnHandleLabel === '保存') {
              this.voucher.id = response.data.id
              const length = response.data.detailList.length
              for (let i = 0; i < length; i++) {
                this.list[i].id = response.data.detailList[i].id
              }
            } else {
              this.initFormData()
              this.voucher.fundAccountId = fundAccountId
              this.voucher.voucherWordId = voucherWordId
              this.voucher.accountNum = accountNum
              this.voucher.yearMonth = yearMonth
              this.voucher.accountDate = accountDate
              this.voucher.carryoverRecordId = carryoverRecordId
              this.voucher.id = undefined
              this.list.forEach(item => {
                this.$set(item, 'id', '')
              })
            }
            this.msgSuccess(this.$t('保存成功'))
            if ((this.operateHandle === 'edit' || this.operateHandle === 'copy' || this.operateHandle === 'insert') && this.$parent.$parent) {
              this.$parent.$parent.formOpen = false
              this.$parent.$parent.getList()
            }
          } else {
            this.msgError(response.msg)
          }
          this.loading = false
        })
      },
      toChineseAmount(n) {
        if (!/^(0|\-*[1-9]\d*)(\.\d+)?$/.test(n)) return ''
        if (n === 0 || !n) return '零元整'
        var fuhao = (n.toString().indexOf('-') === 0 ? '负' : '')
        var unit = '千百拾亿千百拾万千百拾元角分'; var str = ''
            n += '00'
        // 如果是负数就就截取
        if (fuhao === '负') {
        n = n.substring(1, n.length)
        }
        var p = n.indexOf('.')
        if (p >= 0) { n = n.substring(0, p) + n.substr(p + 1, 2) }
        unit = unit.substr(unit.length - n.length)
        for (var i = 0; i < n.length; i++) { str += '零壹贰叁肆伍陆柒捌玖'.charAt(n.charAt(i)) + unit.charAt(i) }
        return fuhao + str.replace(/零(千|百|拾|角)/g, '零').replace(/(零)+/g, '零').replace(/零(万|亿|元)/g, '$1').replace(/(亿)万|壹(拾)/g, '$1$2').replace(/^元零?|零分/g, '').replace(/元$/g, '元整')
      }
    }
  }
  </script>

  <style lang="scss" scoped>
  .display-between{
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 10px;
    .gap10{
        column-gap: 14px;
        display: flex;
        align-items: center;
    }
    .label{
        margin: 0 3px;
    }
  }
  .pad5 > div{
    width: calc(100% - 10px);
    margin: 5px;
  }
  table {
    width: 100%;
    height: 100%;
    border-spacing: 0;
    border-collapse: collapse;
    padding: 0;
    margin: 0;
    td {
      text-align: center;
      table-layout: fixed;
      padding: 0px;
      position: relative;
    }
  }
  .charge-title{
    text-align: center;
    margin: 0;
    padding: 30px 0 50px;
  }

  .main-subject {
    position: relative;
    // height: 60px;
    min-height: 60px;
    text-align: left;
    padding: 5px;
    font-size: 13px;
    word-break: break-all;
    line-height: 18px;
    textarea {
      width: 100%;
      height: 100%;
      padding: 9px 10px;
      overflow: auto;
      resize: none;
      border: none;
      border-radius: 0px;
      margin: 0;
      color: #444;
      box-sizing: border-box;
    }
    .dropdown-menu {
      position: absolute;
      top: 100%;
      left: 0px;
      float: left;
      padding: 5px 0;
      margin: 2px 0 0;
      text-align: left;
      list-style: none;
      background-color: #fff;
      background-clip: padding-box;
    }
    .suggest-list {
      width: 100%;
      height: auto;
      z-index: 1015;
      min-width: inherit;
      display: block;
      overflow: hidden;
      border: none;
      box-shadow: 0 1px 6px rgba(0, 0, 0, .2);
      .item-list {
        max-height: 240px;
        overflow: auto;
        list-style: none;
        margin: 0px;
        padding: 0px;
        li {
          display: flex;
          padding: 0 10px;
          height: 28px;
          line-height: 28px;
          cursor: pointer;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
          &:hover{
            background: #ecebeb;
          }
        }
        .hover {
          background: #ecebeb;
        }
      }
    }
  }
  .main-subject-input{
    display: flex;
    align-items: center;
    column-gap: 5px;
    .el-icon-check{
      cursor: pointer;
    }
  }

  .charge-container {
     .charge {
        width: 80%;
        margin: auto;
        min-width: 1000px;
        padding: 15px 20px;
        font-size: 14px;
        color: #444;
        font-weight: 400;
        background-color: white;
        position: relative;
        .absolute{
          position: absolute;
          left: 0;
          top: -35px;
          display: flex;
          align-items: center;
          column-gap: 10px;
          font-size: 13px;
        }
    }
  }

  .tip-box-table {
    tr {
        height: 25px;
    }
    td{
        white-space: nowrap;
        font-size: 12px;
        padding: 0 3px;
        text-align: left;
    }
  }

  .charge-table, .tip-box-table {
    border: 1px solid #dadada;
  }

  .charge-table, .debtor-tbale {
    // height: 60px;
    height: 100%;
  }
  .lender-tbale > tr {
    height: 60px;
  }

  .charge-table > tr:first-child {
    height: 50px;
  }

  .charge-table-icon {
    cursor: pointer;
    display: inline-block;
  }

  .debtor-lender-table tr td {
    width: 9%;
    border-right: 1px solid #dadada;
  }

  .debtor-lender-table tr td:nth-child(3) {
    border-right-color: #ABDBF5;
  }

  .debtor-lender-table tr td:nth-child(6) {
    border-right-color: #A8D9F5;
  }

  .debtor-lender-table tr td:nth-child(9) {
    border-right-color: #EEBDBD;
  }

  .debtor-lender-table tr td:last-child {
    border-right: none;
  }
  .bold{
    font-family: tahoma;
    font-weight: bold;
  }
  .red{
    color: red;
  }
  .auxiliaryDiv{
    display: flex;
    align-items: center;
    >span{
      white-space: nowrap;
      width: 65px;
      color: #999999;
      font-weight: 400;
    }
  }
  .print-charge-table{
    border-spacing: 0;
    border-collapse: collapse;
    padding: 0;
    margin: 0;
    border: 1px solid #dadada;
    th{
      padding: 10px 5px;
    }
    td {
      >div{
        padding: 10px;
        min-height: 37px;
      }
    }
    .align-left{
      text-align: left;
    }
    .align-right{
      text-align: right;
    }
  }
  #chargeContainer{
    overflow: auto;
    height: 100%;
  }
  .print-charge-table{
    height: auto!important;
  }
</style>
